// ========================================================
// Des：
// Autor：Mr.H 
// CreateTime：2024/04/18 15:16:13
// 版 本：v 1.0
// ========================================================
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Unity.VisualScripting;
using UnityEngine;

public class NetAsyncMgr : MonoBehaviour
{
    private static NetAsyncMgr instance;
    public static NetAsyncMgr Instance => instance;

    private Socket socket;//和服务器进行连接的Socket

    //缓存容器
    private byte[] cacheBytes = new byte[1024 * 1024];
    private int cachNum = 0;


    void Awake()
    {
        instance = this;
        DontDestroyOnLoad(this.gameObject);
    }

    public void Connect(string ip, int port)
    {
        IPEndPoint iPPoint = new(IPAddress.Parse(ip), port);
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        SocketAsyncEventArgs args = new()
        {
            RemoteEndPoint = iPPoint,
        };
        args.Completed += (socket, args) =>
        {
            if (args.SocketError == SocketError.Success)
            {
                Debug.Log("连入成功");
                //收消息
                SocketAsyncEventArgs receiveArgs = new();
                receiveArgs.SetBuffer(cacheBytes, 0, cacheBytes.Length);
                receiveArgs.Completed += ReceiveCallBack;
                this.socket.ReceiveAsync(receiveArgs);
            }
            else
            {
                Debug.Log("连入失败" + args.SocketError);
            }
        };
        socket.ConnectAsync(args);
    }

    /// <summary>
    /// 收消息完成时的回调
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="args"></param>
    private void ReceiveCallBack(object obj, SocketAsyncEventArgs args)
    {

        if (args.SocketError == SocketError.Success)
        {
            Debug.Log("收到消息");
            //解析消息     目前用的字符串规则       
            Debug.Log(Encoding.UTF8.GetString(args.Buffer, 0, args.BytesTransferred));
            //继续去收消息
            args.SetBuffer(0, args.Buffer.Length);
            //继续异步收消息
            if (this.socket != null && this.socket.Connected)
            {
                socket.ReceiveAsync(args);
            }
            else
            {
                Close();
            }

        }
        else
        {
            Debug.Log("接收消息错误" + args.SocketError);
            //关闭客户端
            Close();
        }
    }

    private void Close()
    {
        if (socket != null)
        {
            socket.Shutdown(SocketShutdown.Both);
            socket.Disconnect(false);
            socket.Close();
            socket = null;
        }
    }

    public void Send(string str)
    {
        if (this.socket != null && this.socket.Connected)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            SocketAsyncEventArgs args = new();
            args.SetBuffer(bytes, 0, bytes.Length);
            args.Completed += (socket, args) =>
            {
                if (args.SocketError != SocketError.Success)
                {
                    Debug.Log("发送消息失败" + args.SocketError);
                    Close();
                }
            };
            this.socket.SendAsync(args);
        }
        else
        {
            Close();
        }
    }




}
